﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.IO;

namespace SPRemoteService.WinApp
{
    [ServiceContract]
    public interface IWinAppRemoteService
    {
        [OperationContract]
        bool OpenFile(string siteUrl, string fileUrl);

        [OperationContract]
        bool PageUp();

        [OperationContract]
        bool PageDown();

        [OperationContract]
        bool CloseFile();

        [OperationContract]
        bool SelectTreeNode(string siteUrl, string libraryDisplayName, string libraryid, string folderNames);
    }

    public class WinAppRemoteService : IWinAppRemoteService
    {
        static OfficeUtilities.PowerPointUtilities ppUtil;
        MainForm mainForm = MainForm.CurrentInstance;

        public bool OpenFile(string siteUrl, string fileUrl)
        {
            
            if (Path.GetExtension(fileUrl) != ".ppt" && Path.GetExtension(fileUrl) != ".pptx")
            {
                return false;
            }

            //Download file
            byte[] byteArr = mainForm.Connector.GetDocument(mainForm.Connector.SiteUrl, mainForm.Connector.SiteUrl.ToString() + fileUrl);
            System.IO.Directory.CreateDirectory(@".\Temp");
            string localFileName = @".\Temp\" + Path.GetFileName(fileUrl);
            File.WriteAllBytes(localFileName, byteArr);
            
            //Open file
            ppUtil = new OfficeUtilities.PowerPointUtilities();
            ppUtil.StartPowerPoint();
            return ppUtil.OpenFile(Path.GetFullPath(localFileName));
        }

        public bool PageUp()
        {
            return ppUtil.PageUp();
        }

        public bool PageDown()
        {
            return ppUtil.PageDown();
        }

        public bool CloseFile()
        {
            return ppUtil.Quit();
        }

        public bool SelectTreeNode(string siteUrl, string libraryDisplayName, string libraryid, string folderNames)
        {
            return mainForm.SelectTreeNode(new Uri(siteUrl), libraryDisplayName, libraryid, folderNames);
        }
    }
}
